<template>
  <!-- 评论输入表单 -->
  <div class="form">
    <h3>
      发表评论
      <el-button class="m-small" size="small" type="primary" @click="store.commit(SET_PARENT_COMMENT_ID, -1)"
                 v-show="parentCommentId!==-1">取消回复
      </el-button>
    </h3>
    <el-form :inline="true" :model="commentForm" :rules="formRules" ref="formRef" size="small">
      <el-input :class="'textarea'" type="textarea" :rows="5" v-model="commentForm.content"
                placeholder="评论千万条，友善第一条"
                maxlength="250" show-word-limit :validate-event="false"/>
      <div class="el-form-item el-form-item--small emoji">
        <img style="width: 32px;height: 32px;" src="https://emoji.emojipic.cn/pic/72/apple/grinning-face_1f600.png"
             @click="showEmojiBox">
        <div class="mask" v-show="emojiShow" @click="hideEmojiBox"></div>
        <!--展示表情列表-->
        <div class="emoji-box" v-show="emojiShow">
          <!--现在只有一种表情包-->
          <div class="emoji-title">
            <span>{{ activeEmojiTab === 0 ? 'tv_小电视' : '其他表情包(现在还没有)' }}</span>
          </div>
          <div class="emoji-wrap" v-show="activeEmojiTab===0">
            <div class="emoji-list" v-for="(img,index) in tvMapper" :key="index" @click="insertEmoji(img.name)">
              <img :src="img.src" :title="img.name">
            </div>
          </div>
          <div class="emoji-tabs">
            <a class="tab-link" :class="{'on':activeEmojiTab===0}" @click="activeEmojiTab=0">
              <img src="https://emoji.emojipic.cn/pic/72/apple/grinning-face_1f600.png">
            </a>
          </div>
        </div>
      </div>
      <el-form-item prop="nickname">
        <el-popover ref="nicknamePopover" placement="bottom" trigger="click"
                    content="输入QQ号将自动拉取昵称和头像">
          <template #reference>
            <el-input v-model="commentForm.nickname" placeholder="QQ（必填）" :validate-event="false">
              <i slot="prefix" class="el-input__icon el-icon-user"></i>
            </el-input>
          </template>
        </el-popover>
      </el-form-item>
      <el-form-item prop="email">
        <el-popover ref="emailPopover" placement="bottom" trigger="click" content="用于接收回复邮件">
          <template #reference>
            <el-input v-model="commentForm.email" placeholder="邮箱（必填）" :validate-event="false">
              <i slot="prefix" class="el-input__icon el-icon-message"></i>
            </el-input>
          </template>
        </el-popover>
      </el-form-item>
      <el-form-item>
        <el-popover ref="websitePopover" placement="bottom" trigger="click" content="可以让我参观一下吗😊">
          <template #reference>
            <el-input v-model="commentForm.website" placeholder="https://（可选）">
              <i slot="prefix" class="el-input__icon el-icon-map-location"></i>
            </el-input>
          </template>
        </el-popover>
      </el-form-item>
      <el-form-item label="订阅回复">
        <el-switch v-model="commentForm.notice"></el-switch>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="default" v-throttle="[postForm,`click`,3000]">发表评论</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import {useState} from "@/util/useState";
import {SET_PARENT_COMMENT_ID} from "@/store/mutations-types";
import {nextTick, onMounted, reactive, ref} from "vue";
import {checkEmail} from "@/util/reg";
import tvMapperData from '@/plugins/tvMapper.json'
import {ElNotification} from "element-plus";
import {useStore} from "vuex";

const {parentCommentId, commentForm, commentQuery} = useState(['parentCommentId', 'commentForm', 'commentQuery'])

const formRules = reactive({
  nickname: [
    {required: true, message: '请输入评论昵称'},
    {max: 18, message: '昵称不可多于15个字符'}
  ],
  email: [
    {required: true, message: '请输入评论邮箱'},
    {validator: checkEmail}
  ],
})
const emojiShow = ref(false)
const activeEmojiTab = ref(0)
const tvMapper = tvMapperData
let textarea = null
// start 和 end分别是文本域选择区域的开始部分和结束部分
let start = 0
let end = 0

onMounted(() => {
  textarea = document.querySelector('.el-form textarea')
})

function showEmojiBox() {
  start = textarea.selectionStart
  end = textarea.selectionEnd
  textarea.focus()
  textarea.setSelectionRange(start, end)
  emojiShow.value = !emojiShow.value
}

function insertEmoji(name) {
  let str = commentForm.value.content
  commentForm.value.content = str.substring(0, start) + name + str.substring(end)
  start += name.length
  end = start
  textarea.focus()
  nextTick(() => {
    textarea.setSelectionRange(start, end)
  })
}

function hideEmojiBox() {
  emojiShow.value = false
  textarea.focus()
  textarea.setSelectionRange(start, end)
}

const store = useStore()
const formRef = ref(null)

const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
    } else {
      console.log('error submit!', fields)
    }
  })
}


function postForm() {
  const adminToken = window.localStorage.getItem('adminToken')
  if (adminToken) {
    //博主登录后，localStorage中会存储token，在后端设置属性，可以不校验昵称、邮箱
    if (commentForm.value.content === '' || commentForm.value.content.length > 250) {
      return ElNotification({
        title: '评论失败',
        message: '评论内容有误',
        type: 'warning'
      })
    } else {
      return store.dispatch('submitCommentForm', adminToken)
    }
  }
  const blogToken = window.localStorage.getItem(`blog${commentQuery.value.blogId}`)
  formRef.value.validate(valid => {
    if (!valid || commentForm.value.content === '' || commentForm.value.content.length > 250) {
      ElNotification({
        title: '评论失败',
        message: '请正确填写评论',
        type: 'warning'
      })
    } else {
      store.dispatch('submitCommentForm', blogToken ? blogToken : '')
    }
  })
}

</script>

<style>
.form {
  background: #fff;
  position: relative;
}

.form h3 {
  margin: 5px;
  font-weight: 500 !important;
}

.form .m-small {
  margin-left: 5px;
  padding: 4px 5px;
}

.el-form .textarea {
  margin-top: 5px;
  margin-bottom: 15px;
}

.el-form textarea {
  padding: 6px 8px;
}

.el-form textarea, .el-form input {
  color: black;
}

.el-form .el-form-item__label {
  padding-right: 3px;
}

.emoji {
  margin-right: 5px;
  position: relative;
  user-select: none;
}

.emoji > img {
  cursor: pointer;
  transition: all 0.3s ease-in-out;
  -webkit-transition: all 0.3s ease-in-out;
  -moz-transition: all 0.3s ease-in-out;
  -o-transition: all 0.3s ease-in-out;
}

.emoji > img:hover {
  transform: rotate(360deg);
  -webkit-transform: rotate(360deg);
  -moz-transform: rotate(360deg);
  -o-transform: rotate(360deg);
}

.emoji-box {
  color: #222;
  overflow: visible;
  background: #fff;
  border: 1px solid #E5E9EF;
  box-shadow: 0 11px 12px 0 rgba(106, 115, 133, 0.3);
  border-radius: 8px;
  width: 340px;
  position: absolute;
  top: 40px;
  z-index: 100;
}

.emoji-box * {
  box-sizing: content-box;
}

.emoji-box .emoji-title {
  font-size: 12px;
  line-height: 16px;
  margin: 13px 15px 0;
  color: #757575;
}

.emoji-box .emoji-wrap {
  margin: 6px 11px 0 11px;
  height: 185px;
  overflow: auto;
  word-break: break-word;
}

.emoji-box .emoji-wrap .emoji-list {
  height: 33px;
  color: #111;
  border-radius: 4px;
  transition: background 0.2s;
  display: inline-block;
  outline: 0;
  cursor: pointer;
}

.emoji-box .emoji-wrap .emoji-list:hover {
  background-color: #ddd;
}

.emoji-box .emoji-wrap .emoji-list img {
  margin: 4px;
  width: 25px;
  height: 25px;
}

.emoji-box .emoji-tabs {
  position: relative;
  height: 36px;
  overflow: hidden;
  background-color: #f4f4f4;
  border-radius: 0 0 4px 4px;
}

.emoji-box .emoji-tabs .tab-link {
  cursor: pointer;
  float: left;
  padding: 7px 18px;
  width: 22px;
  height: 22px;
}

.emoji-box .emoji-tabs .tab-link.on {
  background-color: #fff;
}

.emoji-box .emoji-tabs .tab-link img {
  width: 22px;
}

.emoji-box .emoji-tabs .tab-link:hover {
  background: #e7e7e7;
}

.mask {
  pointer-events: auto;
  position: fixed;
  z-index: 99;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}
</style>
